package ws.rest.check.manager;


import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.io.Reader;
import java.util.List;
import java.util.Map;

import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;

import org.apache.wink.server.utils.LinkBuilders;
import org.json.JSONArray;
import org.json.JSONObject;

import ws.rest.check.base.BaseResourceImpl;
import ws.rest.check.validator.CheckItem;
import ws.rest.check.validator.CheckResult;

@Path("validate")
public class CheckContoller {

    private static final String TASK = "validate";
    private static final String ITEM_PATH = "{validate}";
    private static CheckContoller instance = null;
    
    public synchronized static CheckContoller getInstance(){
    	if(instance==null)
    		return new CheckContoller();
    	return instance;
    }
   
    @POST
    @Path("/upload/{id}")
    public void postXML(@PathParam("id") String id,File file){
    	System.out.println(id);
    	Reader reader;
    	LineNumberReader lineReader;
    	StringBuffer sb = new StringBuffer();
		try {
			reader = new FileReader(file);
			lineReader = new LineNumberReader(reader);
		    String line;
		    do {  
		        line = lineReader.readLine();  
		        if (line != null){
		        	sb.append(line);
		        }
		    } while (line != null);  
			lineReader.close();
			reader.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		BaseResourceImpl.getInstance().getCheckXMLsMap().put(id, sb.toString());
    }
    
    @POST
    @Path("/check/{id}")
    @Consumes( { MediaType.APPLICATION_FORM_URLENCODED })
    @Produces( { MediaType.APPLICATION_JSON })
    public JSONObject check(MultivaluedMap<String, String> formData,@Context UriInfo uriInfo,
    		@Context LinkBuilders linksBuilders,@PathParam("id") String id){
    	
    	JSONObject obj = new JSONObject();
    	Map<Object, Object> requestData;
    	CheckResult chkRes;
    	try{
    		requestData = CheckManager.getInstance().pretreatRequestData(formData);
    		
    		chkRes = CheckManager.getInstance().checkRequestData(requestData,id);
        	
    		if(chkRes != null && chkRes.isPassed()==false){
        		List<String> err_msg = chkRes.getErrMsgs(); 
        		StringBuilder sb = new StringBuilder();
        		for(String str:err_msg){
        			sb.append(str);
        		}
    			obj.put("err_msg",sb.toString());
        	}
    	}catch (Exception e) {
            e.printStackTrace();
            throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
        }
    	return obj;
    }
    
    
    @Path(ITEM_PATH)
    @PUT
    @Consumes( { MediaType.APPLICATION_JSON })
    @Produces( { MediaType.APPLICATION_JSON })
    public JSONObject updateTask(JSONObject task, @Context UriInfo uriInfo,
            @Context LinkBuilders linksBuilders) {
        return null;
    }

    @Path(ITEM_PATH)
    @DELETE
    @Produces( { MediaType.APPLICATION_JSON })
    public JSONObject deleteTask(@Context LinkBuilders link, @Context UriInfo uri,
            @PathParam(TASK) String taskId) {
        return null;
    }
}